package update;

import java.util.Arrays;

import protocol.CtfActionException;
import utils.Conversions;

/**
 * Represents a single cell update.
 * @author lilywong
 *
 */
public class CellUpdateBody {
	public static final int LENGTH = 10;
	
	/* Fields set */
	int row;
	int col;
	int cellType;
	int occupiedByPlayer;
	int occupiedByObject;
	
	public int getRow() { return row; }
	public int getCol() { return col; }
	public int getCellType() { return cellType; }
	public int getOccupiedByPlayer() { return occupiedByPlayer; }
	public int getOccupiedByObject() { return occupiedByObject; }
	
	/**
	 * Parses the received byte array. (Client usage)
	 * 
	 * @param response
	 * @throws CtfActionException
	 */
	public CellUpdateBody( byte[] response ) throws CtfActionException {
		byte[] rowInBytes 		= Arrays.copyOfRange(response, 0, 2);
		byte[] colInBytes 		= Arrays.copyOfRange(response, 2, 4);
		byte[] cellTypeInBytes 	= Arrays.copyOfRange(response, 4, 6);
		byte[] playerInBytes 	= Arrays.copyOfRange(response, 6, 8);
		byte[] objectInBytes 	= Arrays.copyOfRange(response, 8, 10);
		// convert back to host byte order
		this.row 				= Conversions.bytesToInt( rowInBytes );
		this.col				= Conversions.bytesToInt( colInBytes );
		this.cellType 			= Conversions.bytesToInt( cellTypeInBytes );
		this.occupiedByPlayer 	= Conversions.bytesToInt( playerInBytes );
		this.occupiedByObject 	= Conversions.bytesToInt( objectInBytes );
		
		// error
		if ( this.row == 0 ) throw new CtfActionException();
	}
	
	public String toString() {
		return "[" + row + "," + col + "," + cellType + "," + occupiedByPlayer+ "," + occupiedByObject+"]";
	}
}
